<?php

namespace app\components\events;

use Yii;
use yii\base\Event;
use yii\web\Response;

class ResponseEvent extends Event
{
    public static function beforeSend($event)
    {
        /** @var Response $response */
        $response = $event->sender;
        $data = $response->data;
        if ($response->getIsEmpty() || is_string($data)) {
            return;
        }

        // 处理code、message
        if (Yii::$app->getErrorHandler()->exception !== null) {
            $code = $data['code'];
            $message = $data['message'];
            if (strpos($message, '|')) {
                list($message, $code) = explode('|', $message);
            }

            $response->data = array_merge($response->data, [
                'code' => (int)$code,
                'message' => $message
            ]);
        }

        // 数据格式重构
        $response->data = [
            'success' => $response->getIsSuccessful(),
            'data' => $response->data,
        ];

        $response->setStatusCode(200);
    }
}